package com.prs.crm.service.fs.impl;

import java.io.File;
import java.util.Collection;

import com.prs.crm.context.Constrains;
import com.prs.crm.context.FileUtil;
import com.prs.crm.dao.fs.OutlayDao;
import com.prs.crm.domain.Attachment;
import com.prs.crm.domain.fs.Detail;
import com.prs.crm.domain.fs.Outlay;
import com.prs.crm.domain.fs.OutlayDetail;
import com.prs.crm.service.fs.DetailService;
import com.prs.crm.service.fs.OutlayDetailService;
import com.prs.crm.service.fs.OutlayService;
import com.prs.crm.service.impl.BaseServiceImpl;

public class OutlayServiceImpl extends BaseServiceImpl<Outlay,OutlayDao> implements OutlayService{
	private DetailService detailService;
	private OutlayDetailService outlayDetailService;
	
	@Override
	public void submitOutlay(Collection<OutlayDetail> outlayDetails,Outlay outlay, File file, String fileName) {
		// TODO Auto-generated method stub
		Attachment attach = FileUtil.getInstance().createAttach(file, fileName);
		if(attach != null) {
			outlay.setAttach(attach);
		}		
		this.getDao().save(outlay);
		
		Double totalMoney = 0.0;		
		for(OutlayDetail outlayDetail : outlayDetails) {
			OutlayDetail detail = new OutlayDetail();
			detail.setMoney(outlayDetail.getMoney());
			detail.setOutlay(outlay);
			detail.setOutlayItem(outlayDetail.getOutlayItem());
			detail.setSummary(outlayDetail.getSummary());
			
			totalMoney += outlayDetail.getMoney();
			this.getOutlayDetailService().save(detail);
		}	
		
		Double sum = this.getDetailService().getBalanceByAccount(outlay.getBankAccount());
		Detail detial = new Detail();
		detial.setOutlay(outlay);
		detial.setIncome(0.0);
		detial.setPay(totalMoney);
		detial.setBalance(sum - totalMoney);
		detial.setBankAccount(outlay.getBankAccount());
		detial.setItem(Constrains.FS_ITEMS_USEOUTLAY);		
		this.getDetailService().save(detial);
	}

	public void setDetailService(DetailService detailService) {
		this.detailService = detailService;
	}

	public DetailService getDetailService() {
		return detailService;
	}

	public void setOutlayDetailService(OutlayDetailService outlayDetailService) {
		this.outlayDetailService = outlayDetailService;
	}

	public OutlayDetailService getOutlayDetailService() {
		return outlayDetailService;
	}

	@Override
	public Collection<Outlay> getMustReturnOutlay() {
		// TODO Auto-generated method stub
		return this.getDao().getMustReturnOutlay();
	}

}
